/*
 * Copyright (c) 2025 Hunan Talkweb Cloud Innovation Technology Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import * as fs from 'fs';
import * as path from 'path';
import { capacitorOhosVariables } from '../capacitor.variables';

interface AppConfig {
  app: {
    bundleName: string;
    vendor: string;
    versionCode: number;
    versionName: string;
    icon: string;
    label: string;
  };
}

interface BuildProfile {
  app: {
    signingConfigs: any[];
    products: Array<{
      name: string;
      signingConfig: string;
      compatibleSdkVersion: string;
      runtimeOS: string;
    }>;
  };
  modules: Array<{
    name: string;
    srcPath: string;
    targets: Array<{
      name: string;
      applyToProducts: string[];
    }>;
  }>;
}

function updateAppConfig(): void {
  const appConfigPath = path.join(__dirname, '../AppScope/app.json5');
  
  const appConfig: AppConfig = {
    app: {
      bundleName: capacitorOhosVariables.bundleName,
      vendor: capacitorOhosVariables.vendor,
      versionCode: capacitorOhosVariables.versionCode,
      versionName: capacitorOhosVariables.versionName,
      icon: "$media:app_icon",
      label: "$string:app_name"
    }
  };
  
  fs.writeFileSync(appConfigPath, JSON.stringify(appConfig, null, 2));
  console.log('Updated AppScope/app.json5');
}

function updateBuildProfile(): void {
  const buildProfilePath = path.join(__dirname, '../build-profile.json5');
  
  const buildProfile: BuildProfile = {
    app: {
      signingConfigs: [],
      products: [
        {
          name: "default",
          signingConfig: "default",
          compatibleSdkVersion: capacitorOhosVariables.compatibleSdkVersion,
          runtimeOS: capacitorOhosVariables.runtimeOS
        }
      ]
    },
    modules: [
      {
        name: capacitorOhosVariables.entryModuleName,
        srcPath: "./entry",
        targets: [
          {
            name: "default",
            applyToProducts: ["default"]
          }
        ]
      }
    ]
  };
  
  fs.writeFileSync(buildProfilePath, JSON.stringify(buildProfile, null, 2));
  console.log('Updated build-profile.json5');
}

// Execute the updates
updateAppConfig();
updateBuildProfile();

console.log('All configuration files updated with variables');